import { routerRedux } from 'dva/router';
import { stringify } from 'qs';
import { fromJS } from 'immutable';
import { setAuthority } from '@/utils/authority';
import { getPageQuery } from '@/utils/utils';
import { reloadAuthorized } from '@/utils/Authorized';
import { geeTest, signin, captcha } from '@/services/login';

export const namespace = 'login';
export default {
  namespace,

  state: fromJS({
    errno: -1,
    type: '',
    geeTest: {},
  }),

  effects: {
    * getGeeTest({ payload = {}, callback }, { call, put }) {
      const { errno, data } = yield call(geeTest, payload);
      if (!errno) {
        yield put({
          type: 'saveGeeTest',
          payload: data,
        });
      }
      if (callback) callback({ errno });
    },

    * login({ payload = {} }, { call, put }) {
      const { errno, data } = yield call(signin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: { ...data, errno },
      });
      // Login successfully
      if (!errno) {
        reloadAuthorized();
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        yield put(routerRedux.replace(redirect || '/dashboard/workplace'));
      }
    },

    * getCaptcha({ payload }, { call }) {
      yield call(captcha, payload);
    },

    * logout(_, { put }) {
      yield put({
        type: 'changeLoginStatus',
        payload: {
          errno: -1,
          currentAuthority: 'guest',
        },
      });
      reloadAuthorized();
      yield put(
        routerRedux.push({
          pathname: '/user/signin',
          search: stringify({
            redirect: window.location.href,
          }),
        })
      );
      localStorage.clear();
    },
  },

  reducers: {
    changeLoginStatus(state, { payload }) {
      setAuthority(payload.currentAuthority);
      const new1 = state.set('errno', payload.errno);
      return new1.set('type', payload.type);
    },
    saveGeeTest(state, { payload = {} }) {
      return state.set('geeTest', payload);
    },
  },
};